package com.gitee.feizns.webtemplate.commons.session;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author feizns
 * @since 2019/4/10
 */
public abstract class AbstractSession implements Session {

    /**
     * 最后被访问的时间
     */
    private long lastAccessedTime;

    /**
     * 对于键标识
     */
    private final String token;

    /**
     * 创建时间
     */
    private final long creationTime;

    /**
     * 属性列表
     */
    private final Map<String, Object> attributes;

    /**
     * 是否被销毁
     */
    private volatile boolean isInvalidate;

    public AbstractSession(String key) {
        this.token = key;
        this.attributes = new LinkedHashMap<>();
        this.creationTime = System.currentTimeMillis();
    }

    @Override
    public long getCreationTime() {
        return creationTime;
    }

    @Override
    public String getToken() {
        return token;
    }

    @Override
    public long getLastAccessedTime() {
        return lastAccessedTime;
    }

    @Override
    public Object setAttribute(String name, Object obj) {

        checkInvalidate();

        return attributes.put(name, obj);
    }

    @Override
    public Object getAttribute(String name) {

        checkInvalidate();

        return attributes.get(name);
    }

    @Override
    public void invalidate() {
        checkInvalidate();

        isInvalidate = true;
    }

    private void checkInvalidate() {
        if ( isInvalidate )
            throw new SessionIsInvalidateException();
    }

    /**
     * session 已经被销毁
     */
    static class SessionIsInvalidateException extends RuntimeException {

    }

}
